<?php
/* SVN FILE: $Id: item_mystery.php 247 2009-10-22 15:31:39Z supersmashbrothers $ */
/**
* ibMarket 2
* IP.Board 3.0
* Mystery item
*
* @author $Author: supersmashbrothers $
* @copyright $Copyright$
* @version $Revision: 247 $
* @lastrevision $Date: 2009-10-22 15:31:39 +0000 (Thu, 22 Oct 2009) $
* @modifiedby $LastChangedBy: supersmashbrothers $
* @lastmodified $LastChangedDate: 2009-10-22 15:31:39 +0000 (Thu, 22 Oct 2009) $
* @filesource $URL: http://ipb-ibmarket.googlecode.com/svn/ibmarket2/trunk/admin/applications_addon/other/ibmarket/items/random/item_mystery.php $
*/

class item_mystery extends templateItem
{
	/**
	 * The default name of the item
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $defaultName = "Get A Mystery Thing";
	
	/**
	 * The default description of the item
	 *
	 * @access	protected
	 * @var		string
	 */
	protected $defaultDescription = "Get a any item or get some money. Who knows?";
	
	// Inherited Properties
	/**
	 * Item setting to allow multiple instances within ibMarket 
	 *
	 * @access	protected
	 * @var		boolean
	 */
	protected $allowMultiple = true;
	
	/**
	 * Item specific setting
	 *
	 * @access	protected
	 * @var		array
	 */
	protected $itemSettings = array();
	
	/**
	 * Constructor to setup the item
	 *
	 * @access	public
	 * @param	ipsRegistry	$registry	IPB registry
	 * @param	array		&$item		The item information
	 */
	public function __construct(ipsRegistry $registry, array &$item)
	{
		parent::__construct($registry, $item);
		
		if($item['item_config'] || $item['item_id'] != 0)
		{
			$this->itemSettings = unserialize($item['item_config']);
		}
		else
		{
			$this->itemSettings['percent'] = 50;
			$this->itemSettings['lowest'] = 0;
			$this->itemSettings['highest'] = 1000;
			$this->itemSettings['items'] = array();
			$this->itemSettings['deduct'] = 1;
		}
	}
	
	/**
	 * Additional settings when adding/editing the item
	 *
	 * @access	public
	 * @return	string|bool	string if there is something to edit, false otherwise
	 */
	public function adminForm()
	{
		$items = array();
		foreach($this->caches['market_items'] as $item_id => $item)
		{
			$null = array();
			if(!marketRegistry::getItem($item)->publicOnCreateItem($null))
			{
				continue;
			}
			$text = $item['item_name']." (".$this->lang->words['stock'].": ";
			$text .= numbers::compare($item['stock']) < 0 ? $this->lang->words['infinite'] : $item['stock'];
			$text .= $item['hide_item'] ? ", ".$this->lang->words['hidden'].")" : ")";
			$items[] = array($item_id, $text);
		}
		
		$form['percent'] = ipsRegistry::getClass('output')->formSimpleInput('item[percent]', $this->itemSettings['percent']);
		$form['min'] = marketFormatter::currencyFormat(ipsRegistry::getClass('output')->formSimpleInput('item[lowest]', $this->itemSettings['lowest'], 10));
		$form['max'] = marketFormatter::currencyFormat(ipsRegistry::getClass('output')->formSimpleInput('item[highest]', $this->itemSettings['highest'], 10));
		$form['items'] = ipsRegistry::getClass('output')->formMultiDropdown('item[items][]', $items, $this->itemSettings['items']);
		$form['deduct'] = ipsRegistry::getClass('output')->formYesNo('item[deduct]', $this->itemSettings['deduct']);
		return <<<EOF
				<li>
					<label>{$this->lang->words['min_money']}</label>
					{$form['min']}
				</li>
				<li>
					<label>{$this->lang->words['max_money']}</label>
					{$form['max']}
				</li>
				<li>
					<label>{$this->lang->words['which_random_item']}</label>
					{$form['items']}
				</li>
				<li>
					<label>
						{$this->lang->words['random_item_deduct']}
						<span class="desctext" style='white-space: nowrap'>{$this->lang->words['random_item_deduct_desc']}</span>
					</label>
					{$form['deduct']}
				</li>
				<li>
					<label>
						{$this->lang->words['mystery_percent']}
						<span class="desctext" style='white-space: nowrap'>{$this->lang->words['mystery_percent_desc']}</span>
					</label>
					{$form['percent']}%
				</li>

EOF;
	}
	
	/**
	 * Saving to adding/editing the item
	 *
	 * @access	public
	 * @param	array	&$item_info		The new item information to be stored in the database.
	 * @param	array	[$input]		Relavent input relating to the item
	 * @todo
	 * @return	void
	 */
	public function adminSave(array &$item_info, array $input)
	{
		$setting = array();
		$setting['percent'] = numbers::max(numbers::min(numbers::parseFloat($input['percent']), 100), 0);
		$setting['lowest'] = numbers::parseInt($input['lowest']);
		$setting['highest'] = numbers::parseInt($input['highest']);
		$setting['items'] = is_array($input['items']) ? $input['items'] : array();
		$setting['deduct'] = intval($input['deduct']) & 1;
		
		$item_info['item_config'] = serialize($setting);
	}
	
	/**
	 * When quick saving the price and stock
	 *
	 * @access	public
	 * @param	array	&$item_info		The new item information to be stored in the database.
	 * @param	string	$type			Possible values: 'stockprice', more possibly in the future
	 * @return	void
	 */
	public function adminQuickSave(array &$item_info, $type)
	{
		return;
	}
	
	/**
	 * When removing the item from ibMarket
	 *
	 * @access	public
	 * @return	void
	 */
	public function adminRemove()
	{
		return;
	}
	
	/**
	 * Viewing the file edits if any
	 *
	 * @access	public
	 * @return	string|bool	string if there is something to edit, false otherwise
	 */
	public function adminViewFileEdits()
	{
		return false;
	}
	
	/**
	 * Any admin AJAX functionality
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	void
	 */
	public function adminAjax()
	{
		return;
	}
	
	/**
	 * Check and modify the intentory item information before storing in the database
	 *
	 * @access	public
	 * @param	array	&$invItem		The new inventory item information to be stored in the database.
	 * @return	bool	true if the item is successfully created, false otherwise
	 */
	public function publicOnCreateItem(array &$invItem)
	{
		return true;
	}
	
	/**
	 * When using the item
	 * Show a form and validate the form
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	string|bool				string if there is a form to be used, true if successfully used, false otherwise
	 */
	public function publicUseItem(array &$invItem)
	{
		$this->registry->getClass('class_localization')->loadLanguageFile( array( 'public_items' ) );
		
		
		$items = array();
		foreach($this->itemSettings['items'] as $itemID)
		{
			$null = array();
			if(!is_array($this->caches['market_items'][$itemID]) || !marketRegistry::getItem($this->caches['market_items'][$itemID])->publicOnCreateItem($null) || ($this->itemSettings['deduct'] && $this->caches['market_items'][$itemID]['stock'] == 0))
			{
				continue;
			}
			
			$items[] = $itemID;
		}
		
		if(numbers::compare(numbers::rand(0,100), $this->itemSettings['percent']) <= 0 || count($items) == 0)
		{
			$amount = numbers::rand($this->itemSettings['lowest'], $this->itemSettings['highest']);
			marketRegistry::recordReward($amount);
			
			IPSMember::save( $this->memberData['member_id'], array( 'core' => array( $this->settings['market_members_field'] => numbers::add($this->memberData[$this->settings['market_members_field']], $amount) ) ) );
			
			$got = marketFormatter::formatCurrency($amount);
		}
		else
		{
			$itemIDPicked = $items[array_rand($items)];
			
			$newInvItem = array(
								'member_id' => $this->memberData['member_id'],
								'item' => $itemIDPicked,
								'price_bought' => 0,
								'resell_price' => 0,
								'time_bought' => IPS_UNIX_TIME_NOW,
								'settings' => '',
							);
			marketRegistry::getItem($this->caches['market_items'][$itemIDPicked])->publicOnCreateItem($newInvItem);
			
			$this->DB->insert('market_inventory',$newInvItem);
			
			if($this->itemSettings['deduct'])
			{
				if(numbers::compare($this->caches['market_items'][$itemIDPicked]['stock']) > 0)
				{
					$this->caches['market_items'][$itemIDPicked]['stock'] = numbers::subtract($this->caches['market_items'][$itemIDPicked]['stock'], 1);
					if(($this->caches['market_items'][$itemIDPicked]['restock'] == 1 || $this->caches['market_items'][$itemIDPicked]['restock'] == 2) && !$this->caches['market_items'][$itemIDPicked]['restock_time'])
					{
						$this->caches['market_items'][$itemIDPicked]['restock_time'] = marketRegistry::nextRestockTime($this->caches['market_items'][$itemIDPicked]);
					}
					$this->DB->update('market_items',array(
															'stock' => $this->caches['market_items'][$itemIDPicked]['stock'],
															'restock_time' => $this->caches['market_items'][$itemIDPicked]['restock_time'],
								),"item_id=".$itemIDPicked);
					
					ipsRegistry::cache()->rebuildCache('market_items','ibmarket');
				}
			}
			
			$got = $this->caches['market_items'][$itemIDPicked]['item_name'];
		}
		
		$this->writeLog($invItem, "Got ".$got." from mystery item");
		
		$this->deleteItems($invItem);
		
		$this->lang->words['received_x'] = sprintf($this->lang->words['received_x'], $got);
		
		$this->registry->getClass('output')->redirectScreen( $this->lang->words['received_x'], $this->settings['base_url_with_app'] . "module=inventory" );
	}
	
	/**
	 * Any AJAX functionality
	 *
	 * @access	public
	 * @param	array	$invItem		The inventory item
	 * @return	void
	 */
	public function publicAjax(array &$invItem)
	{
		return;
	}
	
	/**
	 * When the item is being sold back
	 *
	 * @access	public
	 * @param	array	&$invItem	The inventory item information
	 * @return	bool				true if successful, false otherwise
	 */
	public function publicOnResoldItem(array &$invItem)
	{
		return true;
	}
	
	/**
	 * When the item is being restocked
	 *
	 * @access	public
	 * @param	array	&$item	The inventory item information
	 * @return	void
	 */
	public function onItemRestock(array &$item)
	{
		return;
	}
}
